⚡️ Speed up function Error by 37%
#260
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 37% (0.37x) speedup for
Errorinlib/matplotlib/_mathtext.py⏱️ Runtime :
1.02 milliseconds→745 microseconds(best of132runs)📝 Explanation and details
The optimization caches the
Empty().setParseAction(raise_error)parser element to avoid recreating it on every function call, achieving a 36% speedup from 1.02ms to 745μs.Key optimization:
Empty().setParseAction(raise_error)for everyError()call (which was taking 97.3% of execution time), the optimization creates this parser element once and stores it as a function attribute.copy()for safety: Returnse.copy()to ensure each caller gets a fresh parser element without mutation side effects, preserving the original behavior completely.Why this works:
Empty().setParseAction(raise_error)was the bottleneck, taking 2.79ms out of 2.87ms total time in the original versionEmpty()object creation andsetParseAction()method calls have significant overhead when repeatedImpact on workloads:
Based on the function references,
Error()is called fromcmd()helper functions that define TeX commands in matplotlib's math text parser. Thecmd()function creates error handlers for malformed TeX expressions like\frac,\sqrt,\left/\rightdelimiters, etc. Since mathematical text parsing can involve many such commands, this optimization directly benefits:Test results show consistent 20-30% improvements across all test cases, with the largest gain (53%) in the stress test creating 100 different error parsers, demonstrating the optimization scales well with frequent
Error()instantiation.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-Error-mjd1d5mxand push.